#!/usr/bin/env /devel/ringojs/bin/ringo

// Copyright 2012 Jay Young. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview
 *
 * A build script for the project.  For now, all we do is build the templates
 * and automate the transformation of those templates from client-side to
 * server-side coding styles.
 */

addToClasspath('.');
var argParser = new (require('ringo/args').Parser)();

argParser.addOption('t', 'templates', 'templates',
                    'A comma-separated list of template files.');
var args = argParser.parse(Array.prototype.slice.call(arguments, 1));

var templates = args.templates ? args.templates.split(',') : [
  'rdoc/lib/templates/typedef',
  'rdoc/lib/templates/common',
  'rdoc/lib/templates/enum',
  'rdoc/lib/templates/file',
  'rdoc/lib/templates/class',
  'rdoc/lib/templates/usage'
];

var {system} = require('ringo/subprocess'),
    fs = require('fs'),
    strings = require('ringo/utils/strings');


var buildCmd = 'java -jar /devel/clbin/SoyToJsSrcCompiler.jar ' +
               '--codeStyle STRINGBUILDER ' +
               '--shouldProvideRequireSoyNamespaces --outputPathFormat ';

function compileTemplate(template) {
  print('Compiling template ' + template);
  var cmd = buildCmd + template + '.js ' + template + '.soy';
  system(cmd);
}


function transformTemplate(template) {
  var file = template + '.js';
  var text = fs.read(file).split('\n'),
      output = [];

  for (var i = 0, len = text.length; i < len; ++i) {
    var line = text[i];

    // We don't need the provide call, obviously.
    if (line === "goog.provide('exports');") {
      continue;
    }

    // Transform the require
    if (line === "goog.require('soy');") {
      output.push("var soy = require('rdoc/templates/soy').soy;");
      continue;
    }

    // Skip this one
    if (line === "goog.require('soy.StringBuilder');") {
      continue;
    }

    output.push(line);
  }

  fs.write(file, output.join('\n'));
}


for (var i = 0, len = templates.length; i < len; ++i) {
  var template = templates[i];
  compileTemplate(template);
  transformTemplate(template);
}
